package com.timelyshopping.common.filters;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;



/**
 * 
 * 验证session用户和页面缓存问题处理
 * 
 * @author chenjing
 * 
 */
public class AuthenticationFilter implements Filter {

	private FilterConfig filterConfig;
	private String onErrorUrl;
//	private Configuration cfg;
//	private ILogService logService;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain next) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession httpSession = httpRequest.getSession();

		/**
		 * @author chenjing
		 * @see 页面缓存设定 <br>
		 *      确保浏览器不缓存页面数据
		 */
		httpResponse.setHeader("Cache-Control", "no-cache");
		httpResponse.setHeader("Cache-Control", "no-store");
		httpResponse.setDateHeader("Expires", 0);
		httpResponse.setHeader("Pragma", "no-cache");

		/**
		 * @author chenjing
		 * @see 过滤未登录用户无效请求 <br>
		 *      未登录用户请求跳转到/user/user-tologin.do
		 */
		String host = httpRequest.getRequestURI();
//		if (httpSession.getAttribute(BaseAction.CURRENT_LOGIN_USER) == null
//				&& host != "/" && (!host.equals("/"))) {
//			boolean validateUrl = false;
//			for (String s : cfg.readAllProperties()) {
//				if (host.indexOf(s.trim()) != -1) {
//					validateUrl = true;
//					break;
//				}
//			}
//			if (validateUrl == false) {
//				httpSession.setAttribute(BaseAction.NOLOGINURL, host);
//				String basePath = request.getScheme() + "://"
//						+ request.getServerName() + ":"
//						+ request.getServerPort()
//						+ httpRequest.getContextPath() + "/";
//				httpResponse.sendRedirect(basePath + onErrorUrl);
//			} else {
//				log(httpRequest, host);
//				next.doFilter(request, response);
//			}
//		} else {
			log(httpRequest, host);
			next.doFilter(request, response);
//		}
	}

	/**
	 * 记录日志
	 * 
	 * @param request
	 */
	private void log(HttpServletRequest request, String host) {
		// 操作日志
//		if (request.getSession().getAttribute(BaseAction.CURRENT_LOGIN_USER) != null
//				&& host != "/" && (!host.equals("/"))) {
//			if ((host.indexOf(".do") != -1)
//					&& (host.indexOf("/dictionarys/dictionarys") == -1)) {
//				String operaturl = host;
//				String operatparams = "";
//				if (host.indexOf("?") != -1) {
//					operaturl = host.substring(0, host.indexOf("?"));
//					operatparams = host.substring(host.indexOf("?") + 1);
//				}
//				String operatmodule = getRequestModule(host);
//
//				SystemLog log = new SystemLog();
//				User user = (User) request.getSession().getAttribute(
//						BaseAction.CURRENT_LOGIN_USER);
//				String operattime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
//						.format(Calendar.getInstance().getTime());
//
//				HttpReqHeader httpreqheader = (HttpReqHeader) request
//						.getSession().getAttribute("httpReqHeader");
//				String service = "pc";
//				if (httpreqheader != null
//						&& httpreqheader.getRecvaddress() != null) {
//					service = httpreqheader.getRecvaddress();
//				}
//				log.setOperatip(FileToolUtils.getIpAddr(request));
//				log.setOperatmodule(operatmodule);
//				log.setOperatparams(operatparams);
//				log.setOperattime(operattime);
//				log.setOperaturl(operaturl);
//				log.setService(service);
//				log.setUsername(user.getUsername());
//
//				//logService.log(log);
//			}
//		}
	}

	/**
	 * 获取操作模块
	 * 
	 * @param host
	 * @return
	 */
	private String getRequestModule(String host) {
		String model = "";
		if (host.indexOf("user/user-login.do") != -1) {
			model = "用户登录";
		} else if (host.indexOf("userinfo/userinfo-tolist.do") != -1) {
			model = "用户列表";
		}
		return model;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		filterConfig = config;
		onErrorUrl = filterConfig.getInitParameter("onError");
		if (onErrorUrl == null || "".equals(onErrorUrl)) {
			onErrorUrl = "onError";
		}
//		cfg = new Configuration().getConfiguration("filterpath.properties");
//		WebApplicationContext springContext = WebApplicationContextUtils
//				.getWebApplicationContext(filterConfig.getServletContext());
//		logService = (ILogService) springContext.getBean("LogService");
	}

	@Override
	public void destroy() {
		filterConfig = null;
		onErrorUrl = null;
//		cfg = null;
//		logService = null;
	}
}